package com.nlelpct.manage.hanlder;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.nlelpct.manage.constant.SecurityConstant;
import com.nlelpct.manage.model.security.MyUser;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * @author :小马
 * @date : 2023-07-12
 */
public class TokenLogoutHandler implements LogoutHandler {
    private final RedisTemplate<String, Object> redisTemplate;

    public TokenLogoutHandler(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        //从请求头中获取token
        String token = request.getHeader(SecurityConstant.SECURITY_TOKEN);
        if (!ObjectUtil.isEmpty(token)) {
            // 删除redis中的数据
            String tokenString = Optional.ofNullable(redisTemplate.opsForValue().get(token)).orElse("").toString();
            redisTemplate.delete(token);
            if (!ObjectUtils.isEmpty(tokenString)) {
                MyUser myUser = JSON.parseObject(tokenString, MyUser.class);
                redisTemplate.delete(myUser.getUserId());
            }
        }
    }
}
